package com.hk.shop.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.springframework.stereotype.Repository;

import com.hk.shop.base.dao.BaseDaoImpl;
import com.hk.shop.dao.ProductDao;
import com.hk.shop.model.Product;
import com.hk.shop.page.PageInfo;

@Repository("productDao")
public class ProductDaoImpl extends BaseDaoImpl<Product, Integer> implements ProductDao {

final String selecthql = "select p ";
	
	public Long CountPageProductFromCategory(Integer cid) {
		String hql = "select count(*) from Product p, Category c, CategorySecond cs ";
		hql += "where p.categorySecond.csid = cs.csid and cs.category.cid = c.cid and c.cid = ?";
		Object[] objs = {cid};
		return count(hql, objs);
	}

	public Long CountPageProductFromCategorySecond(Integer csid) {
		String hql = "select count(*) from Product p ,CategorySecond cs ";
		hql += "where p.categorySecond.csid = cs.csid and cs.csid = ?";
		Object[] objs = {csid};
		return count(hql, objs);
	}

	public Long CountProduct() {
		String hql = "select count(*) from Product";
		return count(hql, null);
	}

	public List<Product> findByCategorySecondCategoryCid(Integer cid,
			Integer page) {
		String hql = selecthql + "from Product p,Category c, CategorySecond cs ";
		hql += "where p.categorySecond.csid = cs.csid and cs.category.cid = c.cid and c.cid = ?";
		return Query(cid, page, hql);
	}

	public List<Product> findByCategorySecondCsid(Integer csid, Integer page) {
		String hql = selecthql + "from Product p ,CategorySecond cs ";
		hql += "where p.categorySecond.csid = cs.csid and cs.csid = ?";
		return Query(csid, page, hql);
	}
	
	private List<Product> Query(Integer csid, Integer page,String hql){
		int rows = 12;
		Query query = this.getCurrentSession().createQuery(hql);
		query.setParameter(0, csid);
		List<Product> list= query.setFirstResult((page - 1) * rows).setMaxResults(rows).list();
		return list;
	}
	
	public List<Product> findHot() {
		String hql = "from Product p where p.is_hot = 1 ";
		hql += "order by p.pdate desc";
		int rows = 10;
		int page1 = 1;
		return findPage(new PageInfo(page1,rows) , hql).getContentList(); 
	}

	public Product findOne(Integer pid) {
		String hql = "from Product p where p.pid = ?";
		Query query = this.getCurrentSession().createQuery(hql);
		query.setParameter(0, pid);
		return (Product)query.uniqueResult(); 
	}

	public List<Product> findNew() {
		String hql = "from Product p ";
		hql += "order by p.pdate desc";
		int rows = 10;
		int page1 = 1;
		return findPage(new PageInfo(page1,rows) , hql).getContentList(); 
	}

	public List<Product> findAll(Integer page) {
		String hql = "from Product";
		int rows = 12;
		int page1 = page;
		return findPage(new PageInfo(page1,rows) , hql).getContentList(); 
	}


}
